const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { Logger } = require('../utils/logger');
const { Payment } = require('wechat-pay');
const { authenticateToken } = require('../middleware/auth');

// 微信支付配置
const fs = require('fs');

// 微信支付配置
let wechatPayConfig = {
  partnerKey: process.env.WECHAT_PAY_KEY || 'your_pay_key', // 微信商户平台API密钥(32位字符串)
  appId: process.env.WECHAT_APP_ID || 'your_app_id',
  mchId: process.env.WECHAT_MCH_ID || 'your_mch_id',
  notifyUrl: process.env.BASE_URL ? `${process.env.BASE_URL}/api/payments/callback/notify` : 'http://localhost:3000/api/payments/callback/notify'
};

// 安全加载微信支付证书文件
if (process.env.WECHAT_PFX_PATH) {
  try {
    if (fs.existsSync(process.env.WECHAT_PFX_PATH)) {
      wechatPayConfig.pfx = fs.readFileSync(process.env.WECHAT_PFX_PATH);
      Logger.logInfo('微信支付证书加载成功');
    } else {
      Logger.logWarn(`微信支付证书文件不存在: ${process.env.WECHAT_PFX_PATH}，将使用无证书模式`);
    }
  } catch (error) {
    Logger.logError('微信支付证书加载失败，将使用无证书模式:', error);
  }
}



// 初始化微信支付
const wechatPay = new Payment(wechatPayConfig);

// 微信授权相关配置
const wechatAuthConfig = {
  appId: process.env.WECHAT_APP_ID || 'your_app_id',
  appSecret: process.env.WECHAT_APP_SECRET || 'your_app_secret',
  redirectUri: process.env.WECHAT_REDIRECT_URI || 'http://localhost:8899/api/payments/wechat/callback'
};

// 微信JS-SDK相关
const crypto = require('crypto');

// 缓存access_token和jsapi_ticket
let wechatCache = {
  accessToken: null,
  accessTokenExpires: 0,
  jsapiTicket: null,
  jsapiTicketExpires: 0
};

// 获取微信access_token
async function getWechatAccessToken() {
  // 如果缓存中有未过期的access_token，直接返回
  if (wechatCache.accessToken && wechatCache.accessTokenExpires > Date.now()) {
    return wechatCache.accessToken;
  }
  
  try {
    const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${wechatAuthConfig.appId}&secret=${wechatAuthConfig.appSecret}`;
    const response = await fetch(url);
    
    if (!response.ok) {
      throw new Error(`获取微信access_token请求失败: ${response.status} ${response.statusText}`);
    }
    
    const data = await response.json();
    
    if (data && data.access_token) {
      // 缓存access_token，有效期设为7000秒（微信官方为7200秒，预留200秒缓冲）
      wechatCache.accessToken = data.access_token;
      wechatCache.accessTokenExpires = Date.now() + 7000 * 1000;
      return data.access_token;
    } else {
      throw new Error('获取微信access_token失败: ' + JSON.stringify(data));
    }
  } catch (error) {
    Logger.logError('获取微信access_token失败:', error);
    throw error;
  }
}

// 获取微信jsapi_ticket
async function getWechatJsapiTicket() {
  // 如果缓存中有未过期的jsapi_ticket，直接返回
  if (wechatCache.jsapiTicket && wechatCache.jsapiTicketExpires > Date.now()) {
    return wechatCache.jsapiTicket;
  }
  
  try {
    const accessToken = await getWechatAccessToken();
    const url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${accessToken}&type=jsapi`;
    const response = await fetch(url);
    
    if (!response.ok) {
      throw new Error(`获取微信jsapi_ticket请求失败: ${response.status} ${response.statusText}`);
    }
    
    const data = await response.json();
    
    if (data && data.ticket) {
      // 缓存jsapi_ticket，有效期设为7000秒（微信官方为7200秒，预留200秒缓冲）
      wechatCache.jsapiTicket = data.ticket;
      wechatCache.jsapiTicketExpires = Date.now() + 7000 * 1000;
      return data.ticket;
    } else {
      throw new Error('获取微信jsapi_ticket失败: ' + JSON.stringify(data));
    }
  } catch (error) {
    Logger.logError('获取微信jsapi_ticket失败:', error);
    throw error;
  }
}

// 生成微信JS-SDK签名
function generateWechatSignature(ticket, url) {
  const nonceStr = Math.random().toString(36).substr(2, 15);
  const timestamp = Math.floor(Date.now() / 1000);
  
  // 按照微信签名算法，对所有参数按字典序排序
  const string1 = `jsapi_ticket=${ticket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${url}`;
  
  // 使用SHA1算法生成签名
  const signature = crypto.createHash('sha1').update(string1).digest('hex');
  
  return {
    appId: wechatAuthConfig.appId,
    timestamp,
    nonceStr,
    signature
  };
}

/**
 * @swagger
 * /api/payments/wechat/share/signature:
 *   post:
 *     summary: 获取微信公众号分享签名
 *     tags: [Payments]
 *     description: 获取微信公众号JS-SDK分享所需的签名等信息
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - url
 *             properties:
 *               url:
 *                 type: string
 *                 description: 当前网页的完整URL，不包含#及其后面部分
 *     responses:
 *       200:
 *         description: 成功获取签名信息
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: 获取成功
 *                 data:
 *                   type: object
 *                   properties:
 *                     appId:
 *                       type: string
 *                       description: 公众号的唯一标识
 *                     timestamp:
 *                       type: integer
 *                       description: 生成签名的时间戳
 *                     nonceStr:
 *                       type: string
 *                       description: 生成签名的随机串
 *                     signature:
 *                       type: string
 *                       description: 签名
 *       400:
 *         description: 参数错误
 *       500:
 *         description: 服务器内部错误
 */
router.post('/wechat/share/signature', async (req, res) => {
  try {
    const { url } = req.body;
    
    if (!url) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数: url'
      });
    }
    
    // 获取jsapi_ticket
    const jsapiTicket = await getWechatJsapiTicket();
    
    // 生成签名
    const signatureData = generateWechatSignature(jsapiTicket, url);
    
    Logger.logInfo('生成微信分享签名成功:', {
      url,
      ...signatureData
    });
    
    res.json({
      code: 200,
      message: '获取成功',
      data: signatureData
    });
    
  } catch (error) {
    Logger.logError('获取微信分享签名失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: process.env.NODE_ENV === 'development' ? error.message : '获取签名失败'
    });
  }
});


/**
 * @swagger
 * tags:
 *   name: Payments
 *   description: 支付管理API
 */

/**
 * @swagger
 * components:
 *   schemas:
 *     Payment:
 *       type: object
 *       properties:
 *         id:
 *           type: integer
 *           description: 支付ID
 *         contract_id:
 *           type: integer
 *           description: 合同ID
 *         user_id:
 *           type: integer
 *           description: 用户ID
 *         payment_no:
 *           type: string
 *           description: 支付单号
 *         amount:
 *           type: number
 *           description: 支付金额
 *         payment_method:
 *           type: string
 *           enum: [alipay, wechat, bank_transfer]
 *           description: 支付方式
 *         status:
 *           type: string
 *           enum: [pending, paid, failed, cancelled, refunded]
 *           description: 支付状态
 *         trade_no:
 *           type: string
 *           description: 第三方交易号
 *         paid_at:
 *           type: string
 *           format: date-time
 *           description: 支付时间
 *         created_at:
 *           type: string
 *           format: date-time
 *           description: 创建时间
 *         updated_at:
 *           type: string
 *           format: date-time
 *           description: 更新时间
 */

/**
 * @swagger
 * /api/payments/create:
 *   post:
 *     summary: 创建支付订单
 *     tags: [Payments]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - contract_id
 *               - amount
 *               - payment_method
 *             properties:
 *               contract_id:
 *                 type: integer
 *                 description: 合同ID
 *               amount:
 *                 type: number
 *                 description: 支付金额
 *               payment_method:
 *                 type: string
 *                 enum: [alipay, wechat, bank_transfer]
 *                 description: 支付方式
 *               openid:
 *                 type: string
 *                 description: 微信用户openid（微信支付时必填）
 *     responses:
 *       200:
 *         description: 支付订单创建成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: "支付订单创建成功"
 *                 data:
 *                   type: object
 *                   properties:
 *                     payment_no:
 *                       type: string
 *                       description: 支付单号
 *                     amount:
 *                       type: number
 *                       description: 支付金额
 *                     payment_method:
 *                       type: string
 *                       description: 支付方式
 *                     payment_url:
 *                       type: string
 *                       description: 支付链接（支付宝等）
 *                     wechat_pay_params:
 *                       type: object
 *                       description: 微信支付调用参数（微信支付时返回）
 *                       properties:
 *                         appId:
 *                           type: string
 *                           description: 微信AppID
 *                         timeStamp:
 *                           type: string
 *                           description: 时间戳
 *                         nonceStr:
 *                           type: string
 *                           description: 随机字符串
 *                         package:
 *                           type: string
 *                           description: 预支付交易会话标识
 *                         signType:
 *                           type: string
 *                           description: 签名类型
 *                         paySign:
 *                           type: string
 *                           description: 支付签名
 *       400:
 *         description: 请求参数错误
 *       500:
 *         description: 服务器内部错误
 */
router.post('/create', async (req, res) => {
  try {
    const { contractId, amount, paymentMethod, contractNumber } = req.body;

    // 验证必填参数
    if (!contractId || !amount || !paymentMethod) {
      return res.status(400).json({
        code: 400,
        message: '缺少必填参数：contractId, amount, paymentMethod'
      });
    }
    // 验证支付方式
    const validMethods = ['alipay', 'wechat', 'bank_transfer'];
    if (!validMethods.includes(paymentMethod)) {
      return res.status(400).json({
        code: 400,
        message: '不支持的支付方式'
      });
    }

    // 验证合同是否存在并获取支付状态
    const [contractRows] = await db.execute(
      'SELECT id, user_id, contract_amount, status, pay_status FROM contracts WHERE id = ?',
      [contractId]
    );

    if (contractRows.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '合同不存在'
      });
    }

    const contract = contractRows[0];

    // 检查合同是否已经支付完成（pay_status=3表示已支付完成）
    if (contract.pay_status === 3) {
      // 合同已支付，不允许重复支付
      return res.status(200).json({
        code: 400,
        message: '该合同已支付完成'
      });
    }

    // 创建支付记录
    const [result] = await db.execute(
      `INSERT INTO payments (
        contract_id, payment_amount, payment_method, payment_date, notes
      ) VALUES (?, ?, ?, CURDATE(), 'pending')`,
      [contractId, amount, paymentMethod]
    );

    // 生成支付单号（使用插入后的ID）
    const payment_no = result.insertId;

    // 更新支付记录的payment_no字段
    await db.execute(
      'UPDATE payments SET payment_no = ? WHERE id = ?',
      [payment_no, payment_no]
    );

    // 更新合同支付状态为2（待支付）
    await db.execute(
      'UPDATE contracts SET pay_status = 2 WHERE id = ?',
      [contractId]
    );

    // 根据支付方式生成支付链接
    let payment_url = null;
    let prepay_id = null;
    
    if (paymentMethod === 'wechat') {
      try {
        console.log('=== 微信支付流程开始 ===');
        console.log('支付单号:', payment_no);
        console.log('支付金额:', amount);
        
        // 获取openid参数
        let { openid, authCode } = req.body;
        // 如果没有openid但有code，则通过code获取openid
        if (!openid && authCode) {
          try {
            const tokenUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${wechatAuthConfig.appId}&secret=${wechatAuthConfig.appSecret}&code=${authCode}&grant_type=authorization_code`;            
            const tokenResponse = await fetch(tokenUrl);
            const tokenData = await tokenResponse.json();            
            if (tokenData.errcode) {
              return res.status(400).json({
                code: 400,
                message: '微信授权失败',
                error: tokenData.errmsg
              });
            }
            
            openid = tokenData.openid;
          } catch (authError) {
            return res.status(400).json({
              code: 400,
              message: '获取微信用户信息失败',
              error: authError.message
            });
          }
        }
        
        // 最终验证openid
        if (!openid) {
          return res.status(400).json({
            code: 400,
            message: '微信支付需要openid参数或微信授权code，请先进行微信授权'
          });
        }        
        // 验证appId是否正确配置
        if (!wechatPayConfig.appId || wechatPayConfig.appId === 'your_app_id') {
          throw new Error('微信AppID未正确配置，请检查环境变量WECHAT_APP_ID');
        }        
        // 生成JSAPI支付参数
        const paymentInstance = new Payment(wechatPayConfig);
        
        // 使用getBrandWCPayRequestParams方法生成支付参数（内部会自动调用统一下单）
        const orderParams = {
          body: `合同支付-${contractId}`,
          out_trade_no: payment_no.toString(),
          total_fee: Math.round(parseFloat(amount) * 100),
          spbill_create_ip: req.ip || '127.0.0.1',
          trade_type: 'JSAPI',
          openid: openid || req.body.openid
        };        
        // 使用Promise包装回调函数
        const jsapiParams = await new Promise((resolve, reject) => {
          paymentInstance.getBrandWCPayRequestParams(orderParams, (err, payargs) => {
            if (err) {
              console.log('getBrandWCPayRequestParams错误:', err);
              reject(err);
            } else {
              console.log('getBrandWCPayRequestParams成功:', payargs);
              resolve(payargs);
            }
          });
        });
        
        console.log('最终JSAPI支付参数:', jsapiParams);
        payment_url = jsapiParams; // JSAPI支付返回支付参数对象
        
        Logger.logInfo(`微信JSAPI支付参数生成成功: ${payment_no}`, {
          trade_type: 'JSAPI',
          payment_url: 'JSAPI支付参数'
        });
      } catch (wechatError) {
        console.log('微信支付过程中发生异常:', wechatError.message);
        Logger.logError('微信支付统一下单失败:', wechatError);
        // 如果微信支付失败，返回错误
        return res.status(500).json({
          code: 500,
          message: '微信支付创建失败',
          error: process.env.NODE_ENV === 'development' ? wechatError.message : '支付服务暂时不可用'
        });
      }
    }

    Logger.logInfo(`支付订单创建成功: ${payment_no}`, {
      contractId,
      amount,
      paymentMethod
    });

    // 构造返回数据
    const responseData = {
      payment_no,
      amount,
      paymentMethod
    };
    
    // 根据支付方式添加不同的支付信息
    if (paymentMethod === 'wechat') {
      // JSAPI支付返回支付参数
      responseData.wechat_pay_params = payment_url;
      responseData.payment_type = 'JSAPI';
    } else {
      responseData.payment_url = payment_url; // 其他支付方式的URL
    }
    
    res.json({
      code: 200,
      message: '支付订单创建成功',
      data: responseData
    });

  } catch (error) {
    Logger.logError('创建支付订单失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: process.env.NODE_ENV === 'development' ? error.message : '创建支付订单失败'
    });
  }
});

/**
 * @swagger
 * /api/payments/{payment_no}:
 *   get:
 *     summary: 查询支付订单状态
 *     tags: [Payments]
 *     parameters:
 *       - in: path
 *         name: payment_no
 *         required: true
 *         schema:
 *           type: string
 *         description: 支付单号
 *     responses:
 *       200:
 *         description: 查询成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: "查询成功"
 *                 data:
 *                   $ref: '#/components/schemas/Payment'
 *       404:
 *         description: 支付订单不存在
 *       500:
 *         description: 服务器内部错误
 */
router.get('/:payment_no', async (req, res) => {
  try {
    const { payment_no } = req.params;

    const [rows] = await db.execute(
      `SELECT 
        p.id, p.contract_id, p.payment_no, p.payment_amount, 
        p.payment_method, p.status, p.payment_date, p.notes,
        p.created_at, p.updated_at,
        c.contract_number, c.lender_name, c.borrower_name, c.user_id, c.pay_status
      FROM payments p
      LEFT JOIN contracts c ON p.contract_id = c.id
      WHERE p.payment_no = ?`,
      [payment_no]
    );

    if (rows.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '支付订单不存在'
      });
    }

    const payment = rows[0];

    res.json({
      code: 200,
      message: '查询成功',
      data: {
        id: payment.id,
        contractId: payment.contract_id,
        contractNumber: payment.contract_number,
        userId: payment.user_id,
        paymentNo: payment.payment_no,
        paymentAmount: payment.payment_amount,
        paymentMethod: payment.payment_method,
        status: payment.status,
        paymentDate: payment.payment_date,
        notes: payment.notes,
        createdAt: new Date(payment.created_at).toLocaleString('zh-CN'),
        updatedAt: payment.updated_at ? new Date(payment.updated_at).toLocaleString('zh-CN') : null,
        contractInfo: {
          lenderName: payment.lender_name,
          borrowerName: payment.borrower_name,
          payStatus: payment.pay_status
        }
      }
    });

  } catch (error) {
    Logger.logError('查询支付订单失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: process.env.NODE_ENV === 'development' ? error.message : '查询支付订单失败'
    });
  }
});

/**
 * @swagger
 * /api/payments/callback/notify:
 *   post:
 *     summary: 支付回调通知
 *     tags: [Payments]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - payment_no
 *               - trade_no
 *               - status
 *             properties:
 *               payment_no:
 *                 type: string
 *                 description: 支付单号
 *               trade_no:
 *                 type: string
 *                 description: 第三方交易号
 *               status:
 *                 type: string
 *                 enum: [paid, failed]
 *                 description: 支付状态
 *               paid_amount:
 *                 type: number
 *                 description: 实际支付金额
 *     responses:
 *       200:
 *         description: 回调处理成功
 *       400:
 *         description: 请求参数错误
 *       500:
 *         description: 服务器内部错误
 */
router.post('/callback/notify', async (req, res) => {
  try {
    // 微信支付回调处理
    if (req.headers['content-type'] && req.headers['content-type'].includes('xml')) {
      // 处理微信支付XML回调
      let xmlData = '';
      req.on('data', chunk => {
        xmlData += chunk;
      });
      
      req.on('end', async () => {
        try {
          // 使用 xml2js 手动解析 XML 数据
          const xml2js = require('xml2js');
          const parser = new xml2js.Parser({ trim: true, explicitArray: false });
          
          // 解析 XML 数据
          parser.parseString(xmlData, async (err, result) => {
            if (err) {
              Logger.logError('解析微信支付回调XML失败:', err);
              return res.end('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[XML解析失败]]></return_msg></xml>');
            }
            
            try {
              // 获取回调数据
              const callbackData = result.xml;
              Logger.logInfo('微信支付回调数据:', callbackData);
              
              // 验证签名 (实际项目中应该实现签名验证)
              // TODO: 实现签名验证
              
              if (callbackData.return_code !== 'SUCCESS') {
                Logger.logError('微信支付回调失败:', callbackData);
                return res.end('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[回调处理失败]]></return_msg></xml>');
              }
              
              if (callbackData.result_code !== 'SUCCESS') {
                Logger.logError('微信支付交易失败:', callbackData);
                return res.end('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
              }
              
              const payment_no = callbackData.out_trade_no;
              const trade_no = callbackData.transaction_id;
              const paid_amount = parseInt(callbackData.total_fee) / 100; // 微信支付金额单位为分，需要转换为元
              
              await processPaymentCallback(payment_no, trade_no, 'paid', paid_amount);
              
              // 返回成功响应给微信
              res.end('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
            } catch (error) {
              Logger.logError('处理微信支付回调数据失败:', error);
              res.end('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[处理失败]]></return_msg></xml>');
            }
          });
        } catch (error) {
          Logger.logError('微信支付回调处理失败:', error);
          res.end('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[处理失败]]></return_msg></xml>');
        }
      });
      
      return;
    }
    
    // 处理其他支付方式的JSON回调（如支付宝）
    const { payment_no, trade_no, status, paid_amount } = req.body;

    // 验证必填参数
    if (!payment_no || !trade_no || !status) {
      return res.status(400).json({
        code: 400,
        message: '缺少必填参数：payment_no, trade_no, status'
      });
    }
    
    await processPaymentCallback(payment_no, trade_no, status, paid_amount);
    
    res.json({
      code: 200,
      message: '回调处理成功'
    });

  } catch (error) {
    Logger.logError('支付回调处理失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: process.env.NODE_ENV === 'development' ? error.message : '回调处理失败'
    });
  }
});

// 支付回调处理公共函数
async function processPaymentCallback(payment_no, trade_no, status, paid_amount) {
  // 查询支付订单
  const [rows] = await db.execute(
    'SELECT id, contract_id, payment_amount, status as current_status FROM payments WHERE payment_no = ?',
    [payment_no]
  );

  if (rows.length === 0) {
    throw new Error('支付订单不存在');
  }

  const payment = rows[0];

  // 如果订单已经是最终状态，不允许修改
  if (['paid', 'failed', 'cancelled', 'refunded'].includes(payment.current_status)) {
    Logger.logInfo(`订单状态已是最终状态，无需更新: ${payment_no}`);
    return;
  }

  // 更新支付状态和备注
  let noteUpdate = `支付状态更新为: ${status}`;
  if (trade_no) {
    noteUpdate += `, 交易号: ${trade_no}`;
  }
  if (paid_amount) {
    noteUpdate += `, 支付金额: ${paid_amount}`;
  }

  await db.execute(
    'UPDATE payments SET status = ?, notes = ? WHERE id = ?',
    [status, noteUpdate, payment.id]
  );

  // 如果支付成功，更新合同状态
  if (status === 'paid') {
    try {
      const [result] = await db.execute(
        'UPDATE contracts SET status = 2, pay_status = 3 WHERE id = ?',
        [payment.contract_id]
      );
      
      if (result.affectedRows === 0) {
        Logger.logError(`合同状态更新失败: 找不到合同ID ${payment.contract_id}`);
      } else {
        Logger.logInfo(`合同状态更新成功: ID=${payment.contract_id}, 状态=2, 支付状态=3`);
      }
    } catch (error) {
      Logger.logError(`合同状态更新失败:`, error);
      // 不抛出异常，确保支付状态更新不受影响
    }
  }

  Logger.logInfo(`支付回调处理成功: ${payment_no}`, {
    trade_no,
    status,
    paid_amount,
    contract_id: payment.contract_id,
    payment_id: payment.id
  });
}



/**
 * @swagger
 * /api/payments/{payment_no}/cancel:
 *   post:
 *     summary: 取消支付订单
 *     tags: [Payments]
 *     parameters:
 *       - in: path
 *         name: payment_no
 *         required: true
 *         schema:
 *           type: string
 *         description: 支付单号
 *     responses:
 *       200:
 *         description: 取消成功
 *       400:
 *         description: 订单状态不允许取消
 *       404:
 *         description: 支付订单不存在
 *       500:
 *         description: 服务器内部错误
 */
router.post('/:payment_no/cancel', async (req, res) => {
  try {
    const { payment_no } = req.params;

    // 查询支付订单
    const [rows] = await db.execute(
      'SELECT id, status FROM payments WHERE payment_no = ?',
      [payment_no]
    );

    if (rows.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '支付订单不存在'
      });
    }

    const payment = rows[0];

    // 只有待支付状态的订单可以取消
    if (payment.status !== 'pending') {
      return res.status(400).json({
        code: 400,
        message: '只有待支付状态的订单可以取消'
      });
    }

    // 更新订单状态为已取消
    await db.execute(
      'UPDATE payments SET status = "cancelled", notes = "订单已取消" WHERE id = ?',
      [payment.id]
    );

    Logger.logInfo(`支付订单取消成功: ${payment_no}`);

    res.json({
      code: 200,
      message: '订单取消成功'
    });

  } catch (error) {
    Logger.logError('取消支付订单失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: process.env.NODE_ENV === 'development' ? error.message : '取消支付订单失败'
    });
  }
});

/**
 * @swagger
 * /api/payments/my-payments:
 *   get:
 *     summary: 查询当前用户的支付记录
 *     tags: [Payments]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           default: 1
 *         description: 页码
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           default: 10
 *         description: 每页数量
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *           enum: [pending, paid, failed, cancelled, refunded]
 *         description: 支付状态筛选
 *     responses:
 *       200:
 *         description: 查询成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: "查询成功"
 *                 data:
 *                   type: object
 *                   properties:
 *                     payments:
 *                       type: array
 *                       items:
 *                         $ref: '#/components/schemas/Payment'
 *                     pagination:
 *                       type: object
 *                       properties:
 *                         page:
 *                           type: integer
 *                         limit:
 *                           type: integer
 *                         total:
 *                           type: integer
 *                         totalPages:
 *                           type: integer
 *       401:
 *         description: 未授权访问
 *       500:
 *         description: 服务器内部错误
 */
router.get('/my-payments', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const status = req.query.status;
    const offset = (page - 1) * limit;

    // 构建查询条件
    let whereClause = 'WHERE c.user_id = ?';
    let queryParams = [userId];
    
    if (status) {
      whereClause += ' AND p.status = ?';
      queryParams.push(status);
    }

    // 查询总数
    const [countRows] = await db.execute(
      `SELECT COUNT(*) as total 
       FROM payments p
       LEFT JOIN contracts c ON p.contract_id = c.id
       ${whereClause}`,
      queryParams
    );
    const total = countRows[0].total;

    // 查询支付记录
    const [rows] = await db.execute(
      `SELECT 
        p.id, p.contract_id, p.payment_no, p.payment_amount, 
        p.payment_method, p.status, p.payment_date, p.notes,
        p.created_at, p.updated_at,
        c.contract_number, c.lender_name, c.borrower_name, c.user_id
      FROM payments p
      LEFT JOIN contracts c ON p.contract_id = c.id
      ${whereClause}
      ORDER BY p.created_at DESC
      LIMIT ? OFFSET ?`,
      [...queryParams, limit, offset]
    );

    // 格式化返回数据
    const payments = rows.map(payment => ({
      id: payment.id,
      contractId: payment.contract_id,
      contractNumber: payment.contract_number,
      paymentNo: payment.payment_no,
      paymentAmount: payment.payment_amount,
      paymentMethod: payment.payment_method,
      status: payment.status,
      paymentDate: payment.payment_date,
      notes: payment.notes,
      createdAt: new Date(payment.created_at).toLocaleString('zh-CN'),
      updatedAt: payment.updated_at ? new Date(payment.updated_at).toLocaleString('zh-CN') : null,
      contractInfo: {
        lenderName: payment.lender_name,
        borrowerName: payment.borrower_name
      }
    }));

    const totalPages = Math.ceil(total / limit);

    res.json({
      code: 200,
      message: '查询成功',
      data: {
        payments,
        pagination: {
          page,
          limit,
          total,
          totalPages
        }
      }
    });

  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: process.env.NODE_ENV === 'development' ? error.message : '查询支付记录失败'
    });
  }
});

/**
 * @swagger
 * /api/payments/wechat/callback:
 *   get:
 *     summary: 微信授权回调
 *     tags: [Payments]
 *     parameters:
 *       - in: query
 *         name: code
 *         required: true
 *         schema:
 *           type: string
 *         description: 微信授权码
 *       - in: query
 *         name: state
 *         required: true
 *         schema:
 *           type: string
 *         description: 支付单号
 *     responses:
 *       200:
 *         description: 授权成功，返回支付参数
 *       400:
 *         description: 授权失败
 *       500:
 *         description: 服务器内部错误
 */
// 微信授权接口
router.post('/wechat/auth', async (req, res) => {
  try {
    const { contractNumber } = req.body;

    // 验证必填参数
    if (!contractNumber) {
      return res.status(400).json({
        code: 400,
        message: '缺少必填参数：contractNumber'
      });
    }

    // 通过合同号查询合同信息
    const [contractRows] = await db.execute(
      'SELECT id, user_id, contract_amount, status, contract_number FROM contracts WHERE contract_number = ?',
      [contractNumber]
    );

    if (contractRows.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '合同不存在'
      });
    }

    const contract = contractRows[0];
    const contractId = contract.id;

    // 生成临时状态标识（用于授权回调时识别）
    const state = `${contractId}_${Date.now()}`;
    const redirectUriWithParams = `${wechatAuthConfig.redirectUri}?contractNumber=${contractNumber}`;
    const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${wechatAuthConfig.appId}&redirect_uri=${encodeURIComponent(redirectUriWithParams)}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect`;
    res.json({
      code: 200,
      message: '微信授权URL生成成功',
      data: {
        contractId: contractId,
        contractNumber: contractNumber,
        authUrl: authUrl,
        state: state
      }
    });

  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: process.env.NODE_ENV === 'development' ? error.message : '生成授权URL失败'
    });
  }
});

router.get('/wechat/callback', async (req, res) => {
  try {
    const { code, state, contractNumber } = req.query;    
    if (!code || !state) {
      console.log('缺少必要参数，code或state为空');
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数'
      });
    }
    
    // 解析state获取contractId
    const contractId = state.split('_')[0];
    
    // 步骤2: 通过code换取openid
    const tokenUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${wechatAuthConfig.appId}&secret=${wechatAuthConfig.appSecret}&code=${code}&grant_type=authorization_code`;    
    const tokenResponse = await fetch(tokenUrl);
    const tokenData = await tokenResponse.json();    
    if (tokenData.errcode) {
      return res.status(400).json({
        code: 400,
        message: '微信授权失败',
        error: tokenData.errmsg
      });
    }
    
    const { openid } = tokenData;    
    const [contractRows] = await db.execute(
      'SELECT id, contract_number FROM contracts WHERE id = ?',
      [contractId]
    );
    
    if (contractRows.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '合同不存在'
      });
    }
    
    const contract = contractRows[0];
    
    // 将授权结果重定向到前端页面
    const authData = {
      contract_id: contractId,
      contract_number: contract.contract_number || contractNumber,
      openid: openid,
      auth_success: true
    };
    const encodedData = encodeURIComponent(JSON.stringify(authData));
    
    const redirectUrl = `https://www.stellargang.cn/h5/#/pages/borrow/contractPreview?authData=${encodedData}`;
    res.redirect(redirectUrl);
    
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      error: process.env.NODE_ENV === 'development' ? error.message : '授权处理失败'
    });
  }
});

module.exports = router;